﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class SplitScreenController
{
    private SplitScreenView view = null;
    private Dictionary<string, object> _serverData;
    private UnityEngine.Object personInfo = null;
    private List<ITemplate_Info> items = new List<ITemplate_Info>();
    
    private int count = 0;//显示数量
    private float ScreenW = 0;
    private float perfabW = 0;
    private int currentIndex = 0;

    public SplitScreenController()
    {
        view = GameObject.Find("SplitScreen").GetComponent<SplitScreenView>();
        personInfo = Resources.Load("Prefabs/MainInfo", typeof(GameObject));
     
        listener();
    }

    public void setResolution(Vector2 value)
    {
        view.GetComponent<RectTransform>().sizeDelta = new Vector2(value.x, value.y);
        ScreenW = view.GetComponent<RectTransform>().sizeDelta.x;
        perfabW = ((GameObject)personInfo).GetComponent<RectTransform>().sizeDelta.x;
        count = (int)(Mathf.Ceil(ScreenW / perfabW) + 1);
        view.count = count;
    }

    private void listener()
    {
        GameStatusModel.GetInstance().OnStatusChangeEvent += OnScreenChange;
    }

    private void OnScreenChange(string value)
    {
        if(value == GameStatusModel.SCREEN_PLAY)
        {
            view.GetComponent<RectTransform>().SetAsLastSibling();
            _serverData = LoadingModel.GetInstance().ServerData;
            view.PlayAnim(true);

            InitGame();
        }
    }

    private void InitGame()
    {
        float screenW = Screen.width;
        float screenH = Screen.currentResolution.height;
        
        view.MainRoot.anchoredPosition3D -= new Vector3(0, screenH * .5f, 0);
        //
        ClassifyData();

        Debug.Log("加载完成");
        currentIndex = count;
        Loader.GetInstance().SetSynergyFunc(dalayRun());      
    }

    private void ClassifyData(string classify = null)
    {
        items.Clear();
        Dictionary<string, object> temp = new Dictionary<string, object>();
        if (string.IsNullOrEmpty(classify))
        {
            //显示全部
            temp = _serverData;
        }
        else
        {
            //根据条件分类
            foreach (var item in _serverData)
            {
                Dictionary<string, object> _data = item.Value as Dictionary<string, object>;
                if (_data[""].ToString() == classify) temp.Add(item.Key, item.Value);
            }
        }

        RectTransform rt;
        count = count < temp.Count ? count : temp.Count;
        for (int i = 0; i < count; i++)
        {
            GameObject obj = GameObject.Instantiate(personInfo) as GameObject;
            KeyValuePair<string, object> _data = temp.ElementAt(i);

            obj.name = _data.Key;
            obj.transform.SetParent(view.MainRoot);
            obj.transform.localScale = Vector3.one;
            rt = obj.GetComponent<RectTransform>();
            rt.anchoredPosition3D = new Vector3(i * (rt.sizeDelta.x + view.interval), 0, 0);

            ITemplate_Info item = obj.GetComponent<MainInfoView>();
            item.getData(_data.Value);
            item.Show();
            items.Add(item);
        }
    }

    IEnumerator dalayRun()
    {
        bool isComplete = false;
        while (!isComplete)
        {
            view.MainRoot.anchoredPosition3D = Vector3.Lerp(view.MainRoot.anchoredPosition3D, new Vector3(0, -100, 0), 0.1f);
            yield return new WaitForSeconds(0.02f);
            if (Vector3.Distance(view.MainRoot.anchoredPosition3D, new Vector3(0, -100, 0)) < 0.01f) 
            {
                view.MainRoot.anchoredPosition3D = new Vector3(0, -100, 0);
                break;
            }
        }
        view.PlayAnim(false);
        Loader.GetInstance().SetSynergyFunc(repeatRun());
    }

    IEnumerator repeatRun()
    {
        
        
        float targetLenght = (ScreenW + perfabW) * .5f;
        bool isNew = false;
        
        while (true)
        {
            if (view.runSpeed < 100) view.runSpeed = 100;

            yield return new WaitForFixedUpdate();
            if (view.isRun)
            {
                for (int i = 0; i < items.Count; i++)
                {
                    items[i].Run(view.runSpeed * Time.deltaTime);              //滚动    
                }
                //检查边界
                if (items[0].getRect().anchoredPosition3D.x < -(targetLenght + 100))
                {
                    currentIndex %= _serverData.Count;
                    KeyValuePair<string, object> _data = _serverData.ElementAt(currentIndex);
                    ITemplate_Info temp = items[0];
                    temp.getRect().name = _data.Key;
                    temp.getData(_data.Value);
                    
                    if (currentIndex == 0)
                    {
                        if (items[items.Count - 1].getRect().anchoredPosition3D.x < (ScreenW - perfabW) * .5f - view.interval)
                        {
                            temp.getRect().anchoredPosition3D = new Vector3(targetLenght + 100, 0, 0);
                            isNew = true;
                        }
                        else
                        {
                            isNew = false;
                        }
                        
                    }
                    if(!isNew)
                        temp.getRect().anchoredPosition3D = items[items.Count - 1].getRect().anchoredPosition3D + new Vector3((temp.getRect().sizeDelta.x + view.interval), 0, 0);
                                      
                    temp.getRect().SetAsLastSibling();
                    items.RemoveAt(0);
                    items.Add(temp);
                    currentIndex++;
                }
            }          
        }
    }
}
